package com.cnhis.cloudhealth.clinical.hosdoctor.doctorscheme.bo;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cnhis.cloudhealth.commons.utils.MySqlUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.hosdoctor.doctorscheme.dao.DoctorschemeDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.newid.GetNewId;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;

import net.sf.json.JSONArray;

@Service
public class DoctorschemeBo {
	@Resource
	private DoctorschemeDao doctorschemeDao;
	@Autowired
	private GetNewId getNewId;
	private ModelVo packModelVo(String nid,Map map){
		ModelVo mo = new ModelVo();
		List<Map<String,String>> list = null;
		try {
			list = doctorschemeDao.queryForList(nid,map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(list!=null&&list.size()>0) {

			mo.setList(list);
			mo.setResult(StaticKeys.OH_SUCCESS);
			mo.setTotal(list.size());
		}
		return mo;
	}

	public ModelVo selectSchemeType(){
		return packModelVo("Doctorscheme.1145",null);
	}

	/**
	 * 排序，vaf59和rownr升序
	 */
	private final static Comparator<Map<String, Object>> comparator = new Comparator<Map<String, Object>>() {
		@Override
		public int compare(Map<String, Object> a1, Map<String, Object> a2) {
			int cr = 0;
			int a = Integer.parseInt(a2.get("vaf59").toString()) - Integer.parseInt(a2.get("vaf59").toString());
			if (a != 0)
				cr = (a <= 0) ? 3 : -1;
			else {
				a = Integer.parseInt(a2.get("rownr").toString()) - Integer.parseInt(a2.get("rownr").toString());
				if (a != 0)
					cr = (a <= 0) ? 2 : -2;
			}
			return cr;
		}
	};


	public ModelVo saveScheme(String bbx1, String bdk1, String bar1, String bef1 )throws Exception{
		String resuletMsg = StaticKeys.ERROR;
		// BBX1--方案项目
		Map<String, Object> bbx1Obj = updateBbx1(bbx1);
		if (bbx1Obj == null) {
			return new ModelVo(StaticKeys.ERROR, "方案项目不能为空");
		}
		int bbx01 = MapUtils.getIntValue(bbx1Obj,"bbx01");
		// BDK1--方案别名
		resuletMsg = updateBdk1(bdk1, bbx01);
		if (StaticKeys.ERROR.equals(resuletMsg)) {
			return new ModelVo(StaticKeys.ERROR, "方案信息不能为空");
		}
		Integer bbx15 = MapUtils.getInteger(bbx1Obj,"bbx15");
		// BAR1--诊疗应用表
		resuletMsg = updateBar1(bar1, bbx01, bbx15);
		if (StaticKeys.ERROR.equals(resuletMsg)) {
			return new ModelVo(StaticKeys.ERROR, "诊疗应用信息不能为空");
		}
		// BEF1--方案明细
		resuletMsg = updateBef1(bef1, bbx01);
		if (StaticKeys.ERROR.equals(resuletMsg)) {
			return new ModelVo(StaticKeys.ERROR, "方案明细信息不能为空");
		}
		return new ModelVo(StaticKeys.OH_SUCCESS, "方案保存成功！");
	}
	/**
	 * 操作bbx1表
	 * @param bbx1
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	private Map<String, Object> updateBbx1(String bbx1){
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			if (bbx1 != null && bbx1.length() > 0) {
				Map<String, Object> newMap = new HashMap<String, Object>();
				Map<String, Object> map = (Map<String, Object>) net.sf.json.JSONObject.fromObject(bbx1);
				newMap.putAll(map);
				newMap.put("acf01", map.get("acf01") == null ? 0 : Integer.parseInt(map.get("acf01").toString()));
				newMap.put("bbx25", sdf.parse(map.get("bbx25").toString()));
				newMap.put("bbx01",doctorschemeDao.getSqlSession().selectOne("Doctorscheme.getbbx01"));
				doctorschemeDao.insert("Doctorscheme.insertBbx1",newMap);
				return newMap;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 操作BDK1--方案别名
	 * @param bdk1,
	 * @param bbx01
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String updateBdk1(String bdk1, int bbx01) {
		try {
			// 删除
			doctorschemeDao.delete("Doctorscheme.deleteBdk1ByBbx01",bbx01);
			if (bdk1 != null && bdk1.length() > 0) {
				List<Map<String, Object>> vo = new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> bdk1Array = (List<Map<String, Object>>) JSONArray.fromObject(bdk1);
				for (Map<String, Object> map : bdk1Array) {
					Map<String, Object> valueMap = new HashMap<String, Object>();
					valueMap.put("bdk01", getNewId.nextId());
					valueMap.put("bbx01", bbx01);
					valueMap.put("bdk03", map.get("bdk03"));
					valueMap.put("abbrp", map.get("abbrp"));
					valueMap.put("abbrw", map.get("abbrw"));
					valueMap.put("bdk06", map.get("bdk06"));
					vo.add(valueMap);
				}
				Map<String,Object> pmap = new HashMap<String,Object>();
				pmap.put("bdk1List",vo);
				doctorschemeDao.insert("Doctorscheme.insterBdk1",pmap);
			}
			return StaticKeys.SUCCESS;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return StaticKeys.ERROR;
	}

	/**
	 * 操作BAR1--诊疗应用表
	 * @param bar1
	 * @param bbx01
	 * @param bbx15
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private String updateBar1(String bar1, int bbx01, Integer bbx15) throws Exception {
		try {
			// 删除
			doctorschemeDao.delete("Doctorscheme.deleteBar1ByBbx01",bbx01);
			if (bar1 != null && bar1.length() > 0 && bbx15 != null && bbx15 == 1) {

				List<Map<String, Object>> vo = new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> bar1Array = (List<Map<String, Object>>) JSONArray.fromObject(bar1);
				for (Map<String, Object> map : bar1Array) {
					Map<String, Object> valueMap = new HashMap<String, Object>();
					valueMap.put("bar01", getNewId.nextId());
					valueMap.put("bbx01", bbx01);
					valueMap.put("bck01", map.get("bck01"));
					vo.add(valueMap);
				}
				Map<String,Object> pmap = new HashMap<String,Object>();
				pmap.put("bar1List",vo);
				doctorschemeDao.insert("Doctorscheme.insertBar1List",pmap);
			}
			return StaticKeys.SUCCESS;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return StaticKeys.ERROR;
	}

	/**
	 * 操作BEF1--方案明细
	 * @param bef1
	 * @param bbx01
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String updateBef1(String bef1, int bbx01) {
		try {
			// 删除
			doctorschemeDao.delete("Doctorscheme.deleteBef1ByBbx01",bbx01);
			if (bef1 != null && bef1.length() > 0) {
				List<Map<String, Object>> vo = new ArrayList<Map<String, Object>>();
				List<Map<String, Object>> bef1Array = (List<Map<String, Object>>) JSONArray.fromObject(bef1);
				// 分组统计+排序(序号)
				Map<String, List<Map<String, Object>>> groups = new HashMap<String, List<Map<String, Object>>>();
				for (Map<String, Object> map : bef1Array) {
					if (groups.get(map.get("vaf59").toString()) == null) {
						List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>();
						groupList.add(map);
						groups.put(map.get("vaf59").toString(), groupList);
					} else {
						List<Map<String, Object>> groupList = groups.get(map.get("vaf59").toString());
						groupList.add(map);
						Collections.sort(groupList, comparator);
						groups.put(map.get("vaf59").toString(), groupList);
					}
				}
				// 赋值
				for (Map.Entry<String, List<Map<String, Object>>> entry : groups.entrySet()) {
					List<Map<String, Object>> list = entry.getValue();
					Long lbef01b = null;
					for (Map<String, Object> map : list) {
						Long newBef01 = getNewId.nextId();
						Long lbef01a = 0l;
						// 西药或者中成药
						if (map.get("bda01").toString().equals("1") || map.get("bda01").toString().equals("2")) {
							if (map.get("vaf32").toString().equals("1") && map.get("rownr").toString().equals("0")) {
								lbef01a = 0l;
								lbef01b = newBef01;
							} else {
								lbef01a = lbef01b;
							}
						} else {
							// 方剂或者手术或者检查
							if (map.get("bda01").toString().equals("8") || map.get("bda01").toString().equals("S") || map.get("bda01").toString().equals("E")) {
								if (map.get("rownr").toString().equals("0")) {
									lbef01a = 0l;
									lbef01b = newBef01;
								} else {
									lbef01a = lbef01b;
								}
							} else {
								lbef01a = 0l;
							}
						}
						map.put("bef01", newBef01);
						map.put("bbx01a", bbx01);
						map.put("bbx01b", lbef01a);
						vo.add(map);
					}
				}
				Map<String,Object> pmap = new HashMap<String,Object>();
				pmap.put("bef1List",vo);
				doctorschemeDao.insert("Doctorscheme.insterBef1",pmap);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return StaticKeys.SUCCESS;
	}
	public ModelVo selectAllMedType(){
		return MySqlUtil.packModelVo("Doctorscheme.717",null,doctorschemeDao);
	}
	public ModelVo selectAllMedByType(Map map, int currentPage, int pageSize){
		return MySqlUtil.packModelVoPage("Doctorscheme.726",map,currentPage,pageSize,doctorschemeDao);
	}
	public ModelVo selectMedKnolegeTree(Map map){
		return MySqlUtil.packModelVo("Doctorscheme.1773",map,doctorschemeDao);
	}
	public ModelVo selectMedKnolegeDetail(Map map){
		return MySqlUtil.packModelVo("Doctorscheme.2031",map,doctorschemeDao);
	}
	public ModelVo selectMedKnolegeByKey(Map map,int pageno,int pagesize){
		return MySqlUtil.packModelVoPage("Doctorscheme.2047",map,pageno,pagesize,doctorschemeDao);
	}

}
